package com.lonely.fx;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 * @date: 2022-07-19 13:54
 * @author: ztkj-hzb
 * @description: 进度条
 **/
public class ProgressBarSettingMain extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    /**
     *
     */
    @Override
    public void start(Stage primaryStage) throws Exception {

        HBox hBox = new HBox();

        //TODO 创建进度条,当没有设置进度的时候，样式是来回滚动
        ProgressBar progressBar = new ProgressBar();
        //初始化设置进度，进度之为0~1
        //ProgressBar progressBar = new ProgressBar(0.5);

        //设置当前进度条进度
        //progressBar.setProgress(0.5);
        //设置成-1，则为左右来回滚动
        //progressBar.setProgress(ProgressBar.INDETERMINATE_PROGRESS);

        //设置进度条宽高
        progressBar.setPrefWidth(300);
        progressBar.setPrefHeight(50);

        //案例， 动态进度条
        ProgressBarTask progressBarTask = new ProgressBarTask();
        progressBarTask.setDelay(Duration.millis(1000));
        progressBarTask.setPeriod(Duration.millis(100));
        progressBarTask.start();

        progressBarTask.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) {
                return;
            }

            System.out.println(newValue);
            if (newValue >= 1) {
                progressBarTask.cancel();
                return;
            }

            progressBar.setProgress(newValue);
        });

        hBox.getChildren().addAll(progressBar);
        primaryStage.setScene(new Scene(hBox));
        primaryStage.setWidth(600);
        primaryStage.setHeight(500);
        primaryStage.show();
    }


    private class ProgressBarTask extends ScheduledService<Double> {

        private double size = 0.0;

        /**
         *
         */
        @Override
        protected Task<Double> createTask() {
            return new Task<Double>() {
                @Override
                protected Double call() throws Exception {
                    return size += 0.1;
                }
            };
        }
    }


}
